package com.gjy.nwpufindseats.Fragment;

import java.util.ArrayList;
import com.gjy.nwpufindseats.Activity_ofdSuccess;
import com.gjy.nwpufindseats.MainActivity;
import com.gjy.nwpufindseats.R;

import com.gjy.nwpufindseats.util.JwNetSpider;
import com.gjy.nwpufindseats.util.NetInfo;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class Fragment_offdown extends Fragment implements OnClickListener{
	
	private CheckBox checkA;
	private CheckBox checkC;
	private CheckBox checkD;
	private CheckBox checkG;
	private TextView offdownBtn;
	public static ArrayList<String> ocRoomA;
	public static int loginInfo;
	public String xhString;
	public String passwordString;
	private Handler handlerMsg;
	Handler handler = new Handler();
	View offDown;
	Boolean end=false;
	public static Context mainContext;
	public static NetInfo netInfo = new NetInfo();
	public static SharedPreferences preferences;
	public static ProgressDialog mydialog;
	NotificationManager nm;
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    		Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mainContext = getActivity();
		offDown= inflater.inflate(R.layout.fragment_offdown, container, false);
		if(!netInfo.isNetConnect(mainContext))
    	{
    		Fragment newContent = new Fragment_netFailure();
    		switchFragment(newContent);
    		return offDown;
    	}
    	preferences=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
    	xhString = preferences.getString("xh", "0");//未登录，则返回0，登录返回学号
    	passwordString =  preferences.getString("password", "0");
    	
    
    	if("0".equals(xhString))
    	{
    		Fragment newContent = new Fragment_login();
    		switchFragment(newContent);
    		Toast.makeText(getActivity(), "您还没有登录，请先登录", Toast.LENGTH_SHORT).show();
    		return offDown;
    	}
		checkA = (CheckBox) offDown.findViewById(R.id.checkBox_Xa);
		checkC = (CheckBox) offDown.findViewById(R.id.checkBox_Xc);
		checkD = (CheckBox) offDown.findViewById(R.id.checkBox_Xd);
		checkG = (CheckBox) offDown.findViewById(R.id.checkBox_Xg);
		SharedPreferences downInfo = getActivity().getSharedPreferences("downloaddate", Context.MODE_PRIVATE);
		checkA.setText("教学西楼A座      \n(上次下载:"+downInfo.getString("31", "从未")+")");
		checkC.setText("教学西楼C座      \n(上次下载:"+downInfo.getString("33", "从未")+")");
		checkD.setText("教学西楼D座      \n(上次下载:"+downInfo.getString("34", "从未")+")");
		checkG.setText("研究生西馆        \n(上次下载:"+downInfo.getString("02", "从未")+")");
		offdownBtn = (TextView) offDown.findViewById(R.id.offdownbtn);
		offdownBtn.setOnClickListener(this);
		return offDown;
	}
	//-----------------按钮监听事件
	@Override
	public void onClick(View v) 
	{	
		
		end = false;
		switch (v.getId()) {
		case R.id.offdownbtn: 
			
			if(!checkA.isChecked()&&!checkC.isChecked()&&!checkD.isChecked()&&!checkG.isChecked())
			{
				Toast.makeText(getActivity(), "请至少选择一项进行下载", Toast.LENGTH_SHORT).show();
			}
			else //有勾选项，开始下载
			{
				handlerMsg=new Handler(){
		    		@SuppressWarnings("unused")
					private int message;

					@SuppressWarnings("deprecation")
					public void handleMessage(Message msg){
		    		     
		    		message = (Integer)msg.obj;
			    		if(loginInfo==0)
						{
			    			mydialog.dismiss();
							Toast.makeText(mainContext, "已保存账户密码错误，请修改", Toast.LENGTH_LONG).show();
						}
						else if(loginInfo==1){
							mydialog.dismiss();
							Toast.makeText(mainContext, "教务网瘫痪了。。。", Toast.LENGTH_SHORT).show();
						}
						else{
							mydialog.dismiss();
							Fragment newContent = new Fragment_offdown();
							switchFragment(newContent);
							Toast.makeText(mainContext, "下载完成！", Toast.LENGTH_SHORT).show();
							 Notification notification = new Notification();
							 // 设置显示在手机最上边的状态栏的图标
							 notification.icon = R.drawable.download;
							 notification.tickerText = "“找座儿”离线下载完成！";
							 notification.defaults |= Notification.DEFAULT_VIBRATE;
							 long[] vibrate = {0,100,200,300};
							 notification.vibrate = vibrate;
							 notification.flags= Notification.FLAG_AUTO_CANCEL;
							 CharSequence contentTitle ="找座儿"; // 通知栏标题   
							 CharSequence contentText ="离线下载完成！"; // 通知栏内容 
							 
							 Intent notificationIntent =new Intent(getActivity(), Activity_ofdSuccess.class); // 点击该通知后要跳转的Activity
							 //notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							 PendingIntent contentItent = PendingIntent.getActivity(mainContext, 0, notificationIntent, 0);   
							 notification.setLatestEventInfo(getActivity(), contentTitle, contentText, contentItent);
							 nm = (NotificationManager) 
										getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
							 nm.notify(0, notification);							      
						}
		    		}
		    	};
		    	Thread tProgress = new Thread()
		    	{
		    		public void run()
		    		{
		    			while (!end) 
		                {
		    				Looper.prepare();
		    				mydialog=ProgressDialog.show(getActivity(), "离线下载", "正在下载，请稍候。。。\n（点击返回可隐藏进度条）",true);
		    				mydialog.setIcon(R.drawable.download);
		    				mydialog.setCancelable(true);           
		                    mydialog.show();
		                    Looper.loop();
		                } 
		    		}
		    		
		    	};
		    	tProgress.start();
				Thread tGet = new Thread()
				{
					public void run()
					{
						try {
							if(checkA.isChecked())
							{	
								ocRoomA=JwNetSpider.offDownRoom(mainContext,xhString, passwordString, "31");
							}
							if(checkC.isChecked())
							{	
								ocRoomA=JwNetSpider.offDownRoom(mainContext,xhString, passwordString, "33");
							}
							if(checkD.isChecked())
							{	
								ocRoomA=JwNetSpider.offDownRoom(mainContext,xhString, passwordString, "34");
							}
							if(checkG.isChecked())
							{	
								ocRoomA=JwNetSpider.offDownRoom(mainContext,xhString, passwordString, "02");
							}
							if("0".equals(ocRoomA.get(0)))
							{
								loginInfo = 0;//跳转至登录信息页面，以修改数据
								end = true;
								Message message = Message.obtain();
								message.obj=loginInfo;
								//通过Handler发布传送消息，handler
								handlerMsg.sendMessage(message);
								Fragment newContent= new Fragment_login_info();
		          		    	switchFragment(newContent);
							}
							else if("1".equals(ocRoomA.get(0)))
							{
								loginInfo = 1;//网站数据错误，跳转至"瘫痪"页面
								end = true;
								Message message = Message.obtain();
								message.obj=loginInfo;
								//通过Handler发布传送消息，handler
								handlerMsg.sendMessage(message);
								Fragment newContent= new Fragment_palsy();
		          		    	switchFragment(newContent);
							}
							else {
								loginInfo = 2;//网站数据错误，跳转至"瘫痪"页面
								end = true;
								Message message = Message.obtain();
								message.obj=loginInfo;
								//通过Handler发布传送消息，handler
								handlerMsg.sendMessage(message);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				};
				tGet.start();
			}	
			/*Intent intent = new Intent(getActivity(),Activity_ofdSuccess.class);
			startActivity(intent);*/
			break;
		default:
			break;
		}		
	}
	
    private void switchFragment(Fragment fragment) {
		if (getActivity() == null)
			return;	
			MainActivity ra = (MainActivity) getActivity();
			ra.switchContent(fragment);
		
	}
    public void AlertDialog(View source)
	{
		 new AlertDialog.Builder(getActivity())
			// 设置对话框标题
			.setTitle("离线下载")
			// 设置图标
			.setIcon(R.drawable.download)
			.setMessage("下载进行中，请稍候。。。");
	}
}
